"use strict";

import axios from "axios";
import { ElMessage } from "element-plus";
import router from "/src/router/index";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
    baseURL: "https://www.changeforyou.cn/blogServer/",
    // baseURL: "http://localhost:8080/",
    timeout: 60 * 1000, // Timeout
    withCredentials: true, // Check cross-site Access-Control,
    mode: "cors",
};

// 创建Axios对象
const Axios = axios.create(config);

// 请求拦截器
Axios.interceptors.request.use(
    (config) => {
        // do something before request is sent
        // let each request carry token
        // ['X-Token'] is a custom headers key
        // please modify it according to the actual situation
        // config.headers['X-Token'] = getToken()
        config.headers["Content-Type"] = "application/json;charset=UTF-8";
        // console.log(config.url)
        if (config.url.indexOf("/login") == -1) {
            let token = localStorage.getItem("token")
            config.headers.Authorization = "Bearer " + token;
        }
        return config;
    },
    (error) => {
        // do something with request error
        console.log(error); // for debug
        return Promise.reject(error);
    }
);

// 响应拦截器
Axios.interceptors.response.use(
    function(response) {
        if (response.status == 200 && response.data.status != 0) {
            ElMessage.error(response.data.error);
        }
        return response;
    },
    function(error) {
        if (error.response.status == 403) {
            router.push("/login");
        } else {
            ElMessage.error("服务器错误");
        }
        return Promise.reject(error);
    }
);

// export default Axios;
export default (app) => {
    // 添加全局的方法
    if (undefined != app) {
        app.config.globalProperties.$http = Axios;
        // 添加全局的方法
        app.config.globalProperties.$translate = (key) => {
            return key;
        };
    }
    return Axios;
};
